package com.cjjd.c.feature.mine;

import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.cjjd.c.EventBusKeys;
import com.cjjd.c.R;
import com.cjjd.c.ShareKeys;
import com.cjjd.c.base.BaseFragment;
import com.cjjd.c.bean.CustomInfo;
import com.cjjd.c.bean.HotelQrCodeInfoBean;
import com.cjjd.c.bean.HttpResult;
import com.cjjd.c.bean.UploadBean;
import com.cjjd.c.feature.dialog.TextDialog;
import com.cjjd.c.feature.mine.Integral.IntegralFragment;
import com.cjjd.c.feature.mine.certify.CertifyFragment;
import com.cjjd.c.feature.mine.favorite.FavoriteFragment;
import com.cjjd.c.feature.mine.hkb.HkbFragment;
import com.cjjd.c.feature.mine.information.InformationActivity;
import com.cjjd.c.feature.mine.login.LoginActivity;
import com.cjjd.c.feature.mine.membercard.MemberCardFragment;
import com.cjjd.c.feature.mine.message.MessageFragment;
import com.cjjd.c.feature.mine.order.MyOrderFragment;
import com.cjjd.c.feature.mine.setting.SettingActivity;
import com.cjjd.c.http.CallbackImpl;
import com.cjjd.c.http.JsonUtils;
import com.cjjd.c.utils.DialogUtil;
import com.cjjd.c.utils.FragmentUtil;
import com.cjjd.c.utils.ImageUtil;
import com.cjjd.c.utils.LogUtil;
import com.cjjd.c.utils.PhoneUtil;
import com.cjjd.c.utils.SharePrefUtil;
import com.cjjd.c.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.app.Activity.RESULT_OK;
import static com.bumptech.glide.gifdecoder.GifHeaderParser.TAG;

/**
 * ----------------------------------
 * Created by xyd on 2017/8/9.
 * <p/>
 * 描  述：
 * <p/>
 * 修订历史:
 * ----------------------------------
 */

public class MineFragment extends BaseFragment {


    @Bind(R.id.tv_name)
    TextView tvName;
    @Bind(R.id.iv_message)
    ImageView ivMessage;
    @Bind(R.id.tv_apply_certify)
    TextView tvApplyCertify;
    @Bind(R.id.iv_logo)
    ImageView ivLogo;

    @Override
    public int getContentView() {
        return R.layout.fragment_mine;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        EventBus.getDefault().register(this);
        return rootView;
    }


    public void initView() {

        tvName.setText("未登录");
        ivLogo.setImageResource(R.drawable.main_round);
    }

    private void ChangeUI(CustomInfo.CustomerInfoBean customerInfo) {
        if (customerInfo == null) {
            return;
        }
        if (isDetached() || !isVisible()) {
            return;
        }

        if (!TextUtils.isEmpty(customerInfo.nickName))
            tvName.setText(customerInfo.nickName);

        ImageUtil.displayRoundImage(customerInfo.image, ivLogo, PhoneUtil.dip2px(78));

        SharePrefUtil.saveString(mContext, ShareKeys.Mobile, customerInfo.mobile);
        SharePrefUtil.saveString(mContext, ShareKeys.Name, customerInfo.customerName);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(String event) {

        if (EventBusKeys.LOGOUT.equals(event) ||
                EventBusKeys.unLogin.equals(event)) {
            initView();
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        if (SharePrefUtil.getBoolean(mContext, ShareKeys.isLogin, false)) {

            tvApplyCertify.setVisibility(View.GONE);

            HashMap<String, Object> h1 = new HashMap<>();
            h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
            h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));

            Call<HttpResult<CustomInfo>> call = service.getCustomerInfo(JsonUtils.convertParam("getCustomerInfo", h1));
            call.enqueue(new CallbackImpl<CustomInfo>() {
                @Override
                public void responseSuccess(Call<HttpResult<CustomInfo>> call, Response<HttpResult<CustomInfo>> response) {
                    ChangeUI(response.body().getData().customerInfo);

                }
            });

        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        ButterKnife.unbind(this);
    }


    @OnClick({R.id.iv_message, R.id.tv_apply_certify, R.id.iv_logo,
            R.id.btn_mylist, R.id.btn_my_collect, R.id.btn_my_jf,
            R.id.btn_card, R.id.btn_hkb,
            R.id.ll_cyxx, R.id.btn_setting, R.id.btn_test})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_message:
                if (SharePrefUtil.getBoolean(mContext, ShareKeys.isLogin, false)) {
                    FragmentUtil.replaceWithAddToBack(mContext, new MessageFragment(), R.id.activity_body);
                } else {
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.tv_apply_certify:
                if (SharePrefUtil.getBoolean(mContext, ShareKeys.isLogin, false)) {
                    FragmentUtil.replaceWithAddToBack(mContext, new CertifyFragment(), R.id.activity_body);
                } else {
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.iv_logo:

                if (SharePrefUtil.getBoolean(mContext, ShareKeys.isLogin, false)) {
                    changeHeadImage("上传头像");
                } else {
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                }

                break;

//            case R.id.tv_level: // 钻石卡会员
//                if (SharePrefUtil.getBoolean(mContext, ShareKeys.isLogin, false)) {
//                    FragmentUtil.replaceWithAddToBack(mContext, new LevelFragment(), R.id.activity_body);
//                } else {
//                    Intent intent = new Intent(mContext, LoginActivity.class);
//                    startActivity(intent);
//                }
//                break;
            case R.id.btn_mylist:
                if (SharePrefUtil.getBoolean(mContext, ShareKeys.isLogin, false)) {
                    FragmentUtil.replaceWithAddToBack(mContext, new MyOrderFragment(), R.id.activity_body);
                } else {
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.btn_my_collect:
                if (SharePrefUtil.getBoolean(mContext, ShareKeys.isLogin, false)) {
                    FragmentUtil.replaceWithAddToBack(mContext, new FavoriteFragment(), R.id.activity_body);
                } else {
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.btn_my_jf:
                if (SharePrefUtil.getBoolean(mContext, ShareKeys.isLogin, false)) {
                    FragmentUtil.replaceWithAddToBack(mContext, new IntegralFragment(), R.id.activity_body);
                } else {
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                }
                break;

            case R.id.btn_card:     // 会员卡
                if (SharePrefUtil.getBoolean(mContext, ShareKeys.isLogin, false)) {
                    FragmentUtil.replaceWithAddToBack(mContext, new MemberCardFragment(), R.id.activity_body);
                } else {
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                }
                break;

            case R.id.btn_hkb:     // 好客币
                if (SharePrefUtil.getBoolean(mContext, ShareKeys.isLogin, false)) {
                    FragmentUtil.replaceWithAddToBack(mContext, new HkbFragment(), R.id.activity_body);
                } else {
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.ll_cyxx:
                if (SharePrefUtil.getBoolean(mContext, ShareKeys.isLogin, false)) {
                    Intent inforIntent = new Intent(mContext, InformationActivity.class);
                    startActivity(inforIntent);
                } else {
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.btn_setting:
                if (SharePrefUtil.getBoolean(mContext, ShareKeys.isLogin, false)) {
                    Intent settingIntent = new Intent(mContext, SettingActivity.class);
                    startActivity(settingIntent);
                } else {
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                }
                break;

            case R.id.btn_test:
                // 获取首页广告 getAdvertByCity
                // getAdvertByCity();

                // 获取启动页广告 getStartPicturePath
                //getStartPicturePath();

                // 获取酒店列表
                //getHotelList();

                // 获取酒店电话与订单自动确定时间 getHotelMobileAndTime
                //getHotelMobileAndTime();

                // 微信登录缺少openid
                //wechatLogin();

                //QQ登录  缺少openid
                //qqLogin();

                // 预订单列表
                getCustomerReserveOrderList();
                break;
        }
    }


    // 头像的类型相关
    private static final int PICK_FROM_CAMERA = 1;
    private static final int CROP_FROM_CAMERA = 2;
    private static final int PICK_FROM_FILE = 3;
    private Uri imgUri;

    /**
     * 对头像的操作
     *
     * @param actionName dialog的title
     */
    private void changeHeadImage(String actionName) {

        DialogUtil.showAlertDialog(mContext, actionName, "请选择头像", "相册", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 方式1，直接打开图库，只能选择图库的图片
                Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                // 方式2，会先让用户选择接收到该请求的APP，可以从文件系统直接选取图片
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
                intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                // 设置数据类型  要限制上传到服务器的图片类型时可以直接写如："image/jpeg 、 image/png等的类型"
                intent.setType("image/*");
                startActivityForResult(i, PICK_FROM_FILE);


            }
        }, "拍照", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                imgUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                        "avatar_" + String.valueOf(System.currentTimeMillis())
                                + ".png"));
                Log.e("xyd", "拍照保存的地址是：" + imgUri);
                // 下面这句指定调用相机拍照后的照片存储的路径，这样通过这个uri就可以得到这个照片了
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
                startActivityForResult(intent, PICK_FROM_CAMERA);

            }
        });
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        LogUtil.e("xyd", "resultCode:::" + resultCode + "  requestCode:::" + requestCode);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case PICK_FROM_CAMERA:
                doCrop(ivLogo.getWidth(), ivLogo.getHeight());
                break;
            case PICK_FROM_FILE:
                imgUri = data.getData();
                Log.e("xyd", "头像设置的大小是：" + ivLogo.getWidth() + "+" + ivLogo.getHeight());
                Log.e("xyd", "选择的相册中照片地址是：" + imgUri);
                doCrop(ivLogo.getWidth(), ivLogo.getHeight());
                break;
            case CROP_FROM_CAMERA:
                if (null != data) {
                    setAndUploadCropImg(data);
                }
                break;
        }
    }


    /**
     * 设置头像
     *
     * @param picdata
     */
    private void setAndUploadCropImg(Intent picdata) {
        Bundle bundle = picdata.getExtras();
        if (null != bundle) {
            Bitmap mBitmap = bundle.getParcelable("data");
            String imageUrl = ImageUtil.savePhoto(mContext, mBitmap, false);
            LogUtil.e("xyd", "imageurl路径是" + imageUrl);
            //ImageUtil.displayRoundImage("file://"+imageUrl,ivPersonIcon,PhoneUtil.dip2px(45),R.drawable.my_icon);

            File file = new File(imageUrl);

            final RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);

            DialogUtil.showLoadingDialog(mContext, "照片上传中...");
            Call<HttpResult<UploadBean>> headPic = service.upload(requestBody);
            headPic.enqueue(new CallbackImpl<UploadBean>() {
                @Override
                public void responseSuccess(Call<HttpResult<UploadBean>> call, Response<HttpResult<UploadBean>> response) {
                    UploadBean uploadBean = response.body().getData();
                    if (uploadBean.pics != null && uploadBean.pics.size() > 0) {
                        String imgPath = uploadBean.pics.get(0).imgPath;
                        ImageUtil.displayRoundImage(imgPath, ivLogo, PhoneUtil.dip2px(78));
                        saveCustomerHeadImg(imgPath);
                    }
                }

                @Override
                protected void onRequestFinish() {
                    super.onRequestFinish();
                    dismissDialog();
                }
            });


        }
    }

    /**
     * 保存头像
     *
     * @param imgPath
     */
    private void saveCustomerHeadImg(String imgPath) {

        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        h1.put("image", imgPath);

        Call call = service.saveCustomerHeadImg(JsonUtils.convertParam("saveCustomerHeadImg", h1));
        call.enqueue(new CallbackImpl() {
            @Override
            public void responseSuccess(Call call, Response response) {
                dismissDialog();
                ToastUtil.showToast("头像更换成功");

            }

            @Override
            protected void onRequestFinish() {
                super.onRequestFinish();
                dismissDialog();
            }
        });
    }

    private void dismissDialog() {
        if (!isDetached() && isVisible()) {
            DialogUtil.dismissLoadingDialog(mContext);
        }
    }

    /**
     * 裁剪图片
     */
    private void doCrop(int outputX_PX, int outputY_PX) {

        //
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setType("image/*");
        List<ResolveInfo> list = mContext.getPackageManager().queryIntentActivities(intent, 0);
        int size = list.size();
        Log.e(TAG, "resolveInfo的长度是" + size);

        if (size == 0) {
            //Toast.makeText(this, "can't find crop app", Toast.LENGTH_SHORT).show();
            LogUtil.e("xyd", "000000000");

            return;
        } else {
            intent.setData(imgUri);
            intent.putExtra("outputX", outputX_PX);
            intent.putExtra("outputY", outputY_PX);
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            intent.putExtra("scale", true);
            intent.putExtra("return-data", true);

            // only one
            if (size == 1) {
                Intent i = new Intent(intent);
                ResolveInfo res = list.get(0);
                i.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
                startActivityForResult(i, CROP_FROM_CAMERA);
            }
        }
    }

    private void getCustomerReserveOrderList() {
        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        h1.put("hotelUuid", "731442f18425499b8aa0b05e4fa2d096");

        Call<HttpResult> call = service.getCustomerReserveOrderList(JsonUtils.convertParam("getCustomerReserveOrderList", h1));
        call.enqueue(new Callback<HttpResult>() {
            @Override
            public void onResponse(Call<HttpResult> call, Response<HttpResult> response) {

            }

            @Override
            public void onFailure(Call<HttpResult> call, Throwable t) {

            }
        });
    }

    private void getHotelMessage(){
        DialogUtil.delDialog(mContext);
        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        h1.put("hotelUuid",SharePrefUtil.getString(mContext,ShareKeys.HomeHotelUuid));
        service.getHotelQrCodeInfo(JsonUtils.convertParam("getHotelQrCodeInfo", h1)).enqueue(new CallbackImpl<HotelQrCodeInfoBean>() {
            @Override
            public void responseSuccess(Call<HttpResult<HotelQrCodeInfoBean>> call, Response<HttpResult<HotelQrCodeInfoBean>> response) {

                DialogUtil.dismissLoadingDialog(mContext);
            }

            @Override
            public void onFailure(Call<HttpResult<HotelQrCodeInfoBean>> call, Throwable t) {
                super.onFailure(call, t);
                DialogUtil.dismissLoadingDialog(mContext);
            }

        });

    }

}
